<template>
  <Modal
    v-model="visiable"
    :closable="false"
    :mask-closable="false"
    :title="modalTitle"
  >
    <Form ref="formValidate" :model="formFields" :rules="ruleValidate" :label-width="90" style="width: 400px">
      <FormItem label="架构名称" prop="simpleName">
        <Input v-model="formFields.simpleName" />
      </FormItem>
      <FormItem label="负责人" prop="charge">
        <Input v-model="formFields.charge" />
      </FormItem>
      <FormItem label="备注" prop="description">
        <Input v-model="formFields.description" />
      </FormItem>
    </Form>
    <div slot="footer">
      <Button @click="handleCancel">取消</Button>
      <Button type="primary" @click="handleOk" :loading="isLoading">确定</Button>
    </div>
  </Modal>
</template>
<script>
import { addOrg, editOrg, queryOrgInfo } from '@/api/organization.js'

export default {
  name: 'AddOrgModal',
  props: ['modalTitle'],
  data () {
    return {
      isLoading: false,
      visiable: false,
      isEdit: 'add',
      formFields: {
        simpleName: '',
        charge: '',
        description: '',
        pcode: '0'
      },
      ruleValidate: {
        simpleName: [{ required: true, message: '请填写架构名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
    showModal (type, deptCode) {
      this.visiable = true
      this.isEdit = type

      if (type === 'edit') {
        this.getOrgInfo(deptCode)
      }
      if (type === 'add' && deptCode) {
        this.formFields.pcode = deptCode
      }
    },
    getOrgInfo (code) {
      queryOrgInfo(code).then(response => {
        const { data } = response
        if (data.code === 2000) {
          const { simpleName, charge, description, code } = data.data
          this.formFields = {
            simpleName,
            charge,
            description,
            code
          }
        } else {
          this.$Message.error(data.msg || '系统错误，请稍后再试')
        }
      })
    },
    handleOk () {
      this.$refs['formValidate'].validate((valid) => {
        let messageText = '创建成功'
        let disptch = addOrg
        if (this.isEdit === 'edit') {
          messageText = '编辑成功'
          disptch = editOrg
        }
        this.isLoading = true
        disptch(this.formFields).then((response) => {
          const { data } = response
          if (data.code === 2000) {
            this.$emit('handleSubmit')
            this.visiable = false
            this.$Message.success(messageText)
          } else {
            this.$Message.error(data.msg || '系统错误，请稍后再试')
          }
          this.isLoading = false
        })
      })
    },
    handleCancel () {
      this.visiable = false
    }
  }
}
</script>
